﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;

namespace OutPutExcelTestByOpenXML
{
    class Program
    {
        static void Main(string[] args)
        {
            OutPutExcel();
        }

        private static void OutPutExcel()
        {
            // 1. 開啟 Excel 檔案，取得工作簿
            SpreadsheetDocument document = null ;
            //document = SpreadsheetDocument.Create("", SpreadsheetDocumentType.Workbook);
            using (document = SpreadsheetDocument.Open(@"C:\OpenXML.xlsx", true))
            {
                WorkbookPart wbPart = document.WorkbookPart;
                // 2. 取得工作簿中的工作表，並透過 Linq 判斷工作表是否存在
                Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Sheet1").FirstOrDefault();
                if (theSheet != null)
                {
                    // 3. 建立 Cell 物件，設定寫入位置，格式，資料
                    Cell cell = new Cell() { CellReference = "A1" };
                    cell.DataType = new EnumValue<CellValues>(CellValues.String);
                    cell.CellValue = new CellValue();
                    cell.CellValue.Text = "點部落";
                    // 4. 建立 Row 物件，將 Cell 加入
                    Row theRow = new Row();
                    theRow.InsertAt(cell, 0);
                    // 5. 將 Row 加入工作表中
                    Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(theSheet.Id))).Worksheet;
                    SheetData sheetData = ws.GetFirstChild<SheetData>();
                    sheetData.Append(theRow);
                    // 6. 儲存檔案
                    ws.Save();
                }
            }
            
        }
    }
}
